import { Component, EventEmitter, OnInit, Output, OnDestroy, Input } from '@angular/core';
import { AlarmService } from 'app/pages/traffic-management/traffic-alert/alarm.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { ToolsService, NotificationService } from 'app/shared/service';
import { BullySubjectService } from 'app/shared/service';
import { MESSAGE_CHANNEL, SELECT_OPTIONS } from 'app/app.constants';
import { Subscription } from 'rxjs';
import { PublicService } from 'app/public/public.service';
import * as moment from 'moment';
import { differenceInCalendarDays } from 'date-fns';
import { IncidentService } from '../../incident-record/incident.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'itmp-ir-info-create',
    templateUrl: './ir-info-detail.component.html',
    styleUrls: ['./ir-info-detail.component.css']
})
export class IrInfoCreateComponent implements OnInit, OnDestroy {
    tagPlaceHolder = '';
    @Output() cancelEdit = new EventEmitter<any>();
    @Output() incidentPosition = new EventEmitter<any>();
    @Output() isIrCreated = new EventEmitter<any>();
    @Output() irFinished = new EventEmitter<any>();
    @Output() clickEdit = new EventEmitter<any>();
    @Input() accessButton;
    totalEle: number;
    isVisible = false;
    isForce = false;
    isForceVisible = false;
    validateForm: FormGroup;
    MoreInfo: FormGroup;
    partnerData = [];
    listOfData3 = [];
    incidentId = '';
    isEditable = false; // 是否可编辑
    isClickEdit = true; // 是否处于编辑状态
    ifMoreInfoShow = false;
    isFinishShow = false;
    otherInfoShow = false;
    isUpdate: any = false;
    zoneIdList = [];
    clickBtn: any;
    ir_ID: any;
    subscription: Subscription = null;
    LANE_BLOCKAGES = ['arrow-up.png', 'cross.png'];
    laneBlockagesList = [];
    createAccess = {};
    partnerLoading = false;
    commentLoading = false;
    listOfOption: Array<{ label: string; value: string }> = [
        { label: 'arrow-up.png', value: 'arrow-up.png' },
        { label: 'cross.png', value: 'cross.png' }
    ];
    verificationStatus: Array<any>;
    incidentType: Array<any>;
    sourceType: Array<any>;
    causeList: Array<any>;
    dateRange = [];
    detailItem: any;
    isTaskFromMap = false; // 是否是从地图过来的创建任务
    selectPartner = null;
    isEdit = false;
    today = new Date();
    partnerType: Array<any>;
    hasConfirm = false;
    isAdd = false;
    editCache: { [key: string]: any } = {};
    editCacheComment: { [key: string]: any } = {};
    editCacheTow: { [key: string]: any } = {};
    commentsData = [];
    UserInfo = null;
    isEditComment = false;
    selectComment = null;
    showMoreInfoTable = false;
    modalSpan = null;
    modalTableSpan = null;
    modalWidth = null;
    type = null;
    saveLoading = false;
    accTypeOptions: Array<{ label: string; value: number }> = [
        { label: 'Chain Collision', value: 0 },
        { label: 'Skidded', value: 1 },
        { label: 'Overturned', value: 2 },
        { label: 'Over Height', value: 3 },
        { label: 'Others', value: 4 }
    ];
    roadStateOptions: Array<{ label: string; value: number }> = [
        { label: 'Dry', value: 0 },
        {
            label: 'Damp or Wet',
            value: 1
        }
    ];
    dangerTypeOptions: Array<{ label: string; value: number }> = [
        {
            label: 'Vehicle on fire',
            value: 0
        },
        { label: 'Others', value: 1 }
    ];
    weatherEventOptions: Array<{ label: string; value: number }> = [
        { label: 'Rain', value: 0 },
        { label: 'Wind', value: 1 },
        { label: 'Bush fire', value: 2 },
        { label: 'Haze', value: 3 }
    ];
    weatherDetailOptions: Array<{ label: string; value: number }> = [
        { label: 'Drizzle', value: 0 },
        { label: 'Heavy', value: 1 },
        { label: 'Thunderstorm', value: 2 },
        { label: 'Violent', value: 3 },
        { label: 'Stormy', value: 4 },
        { label: 'Lateral', value: 5 },
        { label: 'In gusts', value: 6 }
    ];
    opinionOptions: Array<{ label: string; value: number }> = [
        { label: 'Event noted', value: 0 },
        { label: '100% reliable forecast', value: 1 },
        { label: 'Probable forecast', value: 2 },
        { label: 'Forecast to be confirmed', value: 3 },
        { label: 'False alarm', value: 4 }
    ];
    visibilityOptions: Array<{ label: string; value: number }> = [
        { label: 'Normal Visibility > 150 meters', value: 0 },
        { label: 'Reduced Visibility < 150 meters', value: 1 },
        { label: 'Greatly Reduced < 50 meters', value: 2 }
    ];
    obstacleTypeOptions: Array<{ label: string; value: number }> = [
        { label: 'Fallen tree', value: 0 },
        { label: 'Oil spill', value: 1 },
        { label: 'Mud spill', value: 2 },
        { label: 'Paint spill', value: 3 },
        { label: 'Flooding', value: 4 },
        { label: 'Pot hole', value: 5 },
        { label: 'Sunken road', value: 6 },
        { label: 'Debris', value: 7 },
        { label: 'Chemical spill', value: 8 },
        { label: 'Man walking', value: 9 },
        { label: 'Slow vehicle', value: 10 },
        { label: 'Others', value: 11 }
    ];
    locationTypeOptions: Array<{ name: string; value: number }> = [
        { name: 'Freeway', value: 0 },
        { name: 'Roads', value: 1 },
        { name: 'Tunnel', value: 2 },
        { name: 'Interchange', value: 3 },
        { name: 'Other', value: 4 }
    ];
    locationSubTypeOptions: Array<{ name: string; value: number }> = [
        { name: 'Road', value: 0 },
        {
            name: 'Junction',
            value: 1
        }
    ];
    roadWorkTypeOptions: Array<{ label: string; value: number }> = [
        { label: 'Plant pruning', value: 0 },
        { label: 'Plant watering', value: 1 },
        { label: 'Lane marking', value: 2 },
        { label: 'Maintenance work', value: 3 },
        { label: 'Road sweeping', value: 4 },
        { label: 'Repair works', value: 5 },
        { label: 'Others', value: 6 }
    ];
    towData = [];
    isEditTow = false;
    towingVehCarType: Array<any>;
    towingType: Array<any>;
    towedVehCarType: Array<any>;
    selectTow = null;
    isAddTow = false;
    isForceFinishVisible = false;
    isCloseShow = false;
    Direction: Array<{ label: string; value: string }> = [
        { label: 'West', value: '0' },
        { label: 'East', value: '1' },
        { label: 'South', value: '2' },
        { label: 'North', value: '3' }
    ];

    constructor(
        private alarmService: AlarmService,
        private fb: FormBuilder,
        private message: NzMessageService,
        private tools: ToolsService,
        private pub: PublicService,
        private bully: BullySubjectService,
        private modalService: NzModalService,
        private msg: NotificationService,
        private incidentService: IncidentService,
        private translate: TranslateService
    ) {}

    getSelectionList() {
        const { res1, res2, res3, res4, res5, res6, res7, res8 } = {
            res1: this.pub.getSelectOptionsList(SELECT_OPTIONS.INCIDENT_STATUS),
            res2: this.pub.getSelectOptionsList(SELECT_OPTIONS.INCIDENT_TYPE),
            res3: this.pub.getSelectOptionsList(SELECT_OPTIONS.INCIDENT_SOURCE),
            res4: this.pub.getSelectOptionsList(SELECT_OPTIONS.PARTNER_TYPE),
            res5: this.pub.getSelectOptionsList(SELECT_OPTIONS.TOWING_VEHICLE_CAR),
            res6: this.pub.getSelectOptionsList(SELECT_OPTIONS.TOWING_TYPE),
            res7: this.pub.getSelectOptionsList(SELECT_OPTIONS.TOWED_VEHCAR),
            res8: this.pub.getSelectOptionsList(SELECT_OPTIONS.CAUSE_TYPE)
        };
        this.verificationStatus = res1.data;
        this.incidentType = res2.data;
        this.sourceType = res3.data;
        this.partnerType = res4.data;
        this.partnerType.sort((a, b) => a.value - b.value);
        this.towingVehCarType = res5.data || [];

        this.towingVehCarType.sort((a, b) => a.value - b.value);
        this.towingType = res6.data || [];

        this.towingType.sort((a, b) => a.value - b.value);
        this.towedVehCarType = res7.data || [];
        this.towedVehCarType.sort((a, b) => a.value - b.value);
        this.causeList = res8.data || [];
    }

    getZoneIdListByUser() {
        const queryData = {
            condition: {
                userId: localStorage.getItem('user_id'),
                user_Name: localStorage.getItem('user_name'),
                user_Pwd: null,
                organization_Id: null,
                userRole_Id: null,
                createTime: {
                    startTime: null,
                    endTime: null
                },
                updateTime: {
                    startTime: null,
                    endTime: null
                }
            },
            pageNum: 1,
            pageSize: 999999
        };
        this.incidentService.getAllUser(queryData).subscribe(res => {
            const userZone = res.content.content[0].userZoneRel;
            userZone.forEach(zoneId => {
                this.zoneIdList.push(zoneId.vnqn_zone_id);
            });
        });
    }

    // 取消强制操作
    FourchHandleCancel() {
        this.isForceVisible = false;
    }

    // 确定强制操作
    ForceHandleOk() {
        this.isForceVisible = false;
        this.isForce = true;
        this.submitForm();
    }

    submitForm(): void {
        const header = {
            zoneId: this.zoneIdList.join(','),
            isFource: this.isForce
        };
        const value = { ir_ID: this.ir_ID, ...this.queryDataForm(this.validateForm.value) };
        for (const i in this.validateForm.controls) {
            if (this.validateForm.controls.hasOwnProperty(i)) {
                this.validateForm.controls[i].markAsDirty();
                this.validateForm.controls[i].updateValueAndValidity();
            }
        }
        if (!this.validateForm.valid) {
            this.message.create('error', `Please  fill in the required items!`);
            return;
        }
        let type = null;
        switch (this.type) {
            case '1':
                if (this.towData.length > 0) {
                    this.towData.forEach((item, index) => {
                        Object.assign(this.towData[index], this.editCacheTow[item.ir_ID].data);
                    });
                }
                this.towData = this.towData.map(item => {
                    delete item.active;
                    return item;
                });
                type = 'IR_Accident';
                break;
            case '2':
                type = 'IR_Weather';
                break;
            case '5':
                type = 'IR_Obstacle';
                break;
            case '7':
                type = 'IR_RoadWork';
                break;
            default:
                break;
        }
        this.towData.forEach(item => {
            if (item.isAdd) {
                delete item.ir_ID;
                delete item.isAdd;
            }
        });
        if (this.type === '1' || this.type === '2' || this.type === '5' || this.type === '7') {
            value.irSub = {
                irsubID: this.MoreInfo.getRawValue().irsubID,
                acc_Type: this.MoreInfo.getRawValue().acc_Type,
                acc_Type_Oth: this.MoreInfo.getRawValue().acc_Type_Oth,
                road_State: this.MoreInfo.getRawValue().road_State,
                fatal_No: this.MoreInfo.getRawValue().fatal_No,
                serious_No: this.MoreInfo.getRawValue().serious_No,
                slight_No: this.MoreInfo.getRawValue().slight_No,
                damage: this.MoreInfo.getRawValue().damage,
                danger_Type: this.MoreInfo.getRawValue().danger_Type,
                danger_Type_Oth: this.MoreInfo.getRawValue().danger_Type_Oth, //  Accident
                time_Of_Removal: this.MoreInfo.getRawValue().time_Of_Removal,
                obstacle_Type: this.MoreInfo.getRawValue().obstacle_Type,
                obstacle_Type_Oth: this.MoreInfo.getRawValue().obstacle_Type_Oth, // Obstacle
                roadWork_Type: this.MoreInfo.getRawValue().roadWork_Type,
                roadWork_Type_Oth: this.MoreInfo.getRawValue().roadWork_Type_Oth,
                permit: this.MoreInfo.getRawValue().permit,
                contractor: this.MoreInfo.getRawValue().contractor,
                supervisor: this.MoreInfo.getRawValue().supervisor,
                handphone: this.MoreInfo.getRawValue().handphone, // RoadWork
                weather_Event: this.MoreInfo.getRawValue().weather_Event,
                weather_Detail: this.MoreInfo.getRawValue().weather_Detail,
                opinion: this.MoreInfo.getRawValue().opinion,
                visibility: this.MoreInfo.getRawValue().visibility, // BadWeather
                tow: this.towData,
                '@type': type
            };
        } else {
            value.irSub = null;
        }
        switch (this.type) {
            case '1':
                if (this.towData.length > 0) {
                    this.towData.forEach((item, index) => {
                        Object.assign(this.towData[index], this.editCacheTow[item.ir_ID].data);
                    });
                }
                this.towData = this.towData.map(item => {
                    delete item.active;
                    return item;
                });
                type = 'IR_Accident';
                break;
            case '2':
                type = 'IR_Weather';
                break;
            case '5':
                type = 'IR_Obstacle';
                break;
            case '7':
                type = 'IR_RoadWork';
                break;
            default:
                value.irSub = null;
                break;
        }

        this.saveLoading = true;
        if (this.isUpdate) {
            if (this.isFinishShow) {
                value.veri_State = 1;
            }

            const query = this.incidentService.updateIrDetail(value, header);
            // query.subscribe(
            //     (res: any) => {
            //         this.saveLoading = false;
            //         if (res['messagecode'] === '000000') {
            //             this.isIrCreated.emit(res.data.ir_ID);
            //             this.isClickEdit = false;
            //             this.clickEdit.emit(false);
            //             this.initIrInfoDetail(res.data);
            //             this.message.create('success', `Update incident record success!`);
            //         }
            //         if (res['messagecode'] === '900103') {
            //             this.isForceVisible = true;
            //         }
            //     },
            //     (error: any) => {
            //         this.message.create('error', `Update incident record failed!`);
            //     }
            // );
        } else {
            value.access = {
                ir_AccessType: false,
                userID: '2051',
                userType: null
            };

            // this.MoreInfo.getRawValue();
            // value.irSub=
            const query = this.alarmService.createIr(value, header);
            query.subscribe(
                (res: any) => {
                    this.saveLoading = false;
                    if (res['messagecode'] === '000000') {
                        this.isIrCreated.emit(res.data.ir_ID);
                        this.isClickEdit = false;
                        this.clickEdit.emit(false);
                        this.initIrInfoDetail(res.data);
                        if (this.isTaskFromMap) {
                            this.incidentPosition.emit(res['data']);
                        }
                        this.message.create('success', `Create incident record success`);
                    } else {
                        this.message.create('error', res.message);
                        if (res['messagecode'] === '900103') {
                            this.isForceVisible = true;
                        }
                    }
                },
                (error: any) => {
                    this.message.create('error', `Create incident record failed!`);
                }
            );
        }
    }

    // get isHorizontal(): boolean {
    //   return this.validateForm.controls.formLayout && this.validateForm.controls.formLayout.value === 'horizontal';
    // }

    initForm() {
        this.validateForm = this.fb.group({
            ir_ID: [{ value: null, disabled: this.isEditable }],
            veri_State: [{ value: null, disabled: this.isEditable }],
            cause_IR_ID: [{ value: null, disabled: this.isEditable }],
            source: [{ value: null, disabled: this.isEditable }, Validators.required],
            type: [{ value: null, disabled: this.isEditable }, Validators.required],
            subType: [{ value: null, disabled: this.isEditable }],
            zone_ID: [{ value: null, disabled: this.isEditable }, Validators.required],
            cause: [{ value: null, disabled: this.isEditable }, Validators.required],
            road_Name: [{ value: null, disabled: this.isEditable }, Validators.required],
            location_Type: [{ value: null, disabled: this.isEditable }, Validators.required],
            location_SubType: [{ value: null, disabled: this.isEditable }],
            direction: [{ value: null, disabled: this.isEditable }, Validators.required],
            start_X_Coor: [{ value: null, disabled: this.isEditable }],
            start_Y_Coor: [{ value: null, disabled: this.isEditable }],
            end_X_Coor: [{ value: null, disabled: this.isEditable }],
            end_Y_Coor: [{ value: null, disabled: this.isEditable }],
            q_End_Link_ID: [{ value: null, disabled: this.isEditable }, Validators.required],
            q_End_X_Coor: [{ value: null, disabled: this.isEditable }],
            q_End_Y_Coor: [{ value: null, disabled: this.isEditable }],
            QEPLatitude: [{ value: null, disabled: this.isEditable }],
            start_Time: [{ value: new Date(), disabled: this.isEditable }],
            end_Time: [{ value: new Date(), disabled: this.isEditable }],
            q_Start_Time: [{ value: new Date(), disabled: this.isEditable }],
            q_End_Time: [{ value: new Date(), disabled: this.isEditable }],
            eTime: [{ value: new Date(), disabled: this.isEditable }, Validators.required],
            Description: [{ value: null, disabled: this.isEditable }],
            remark: [{ value: null, disabled: this.isEditable }],
            lane_Blockage: [{ value: null, disabled: this.isEditable }, Validators.required],
            relatedIncident: [{ value: null, disabled: this.isEditable }],
            irSub: [{ value: null, disabled: this.isEditable }],
            access: [{ value: null, disabled: this.isEditable }],
            startCoor: [{ value: null, disabled: this.isEditable }, Validators.required],
            endCoor: [{ value: null, disabled: this.isEditable }, Validators.required],
            QendCoor: [{ value: null, disabled: this.isEditable }, Validators.required],
            incidentTimeRange: [{ value: null, disabled: this.isEditable }],
            QTimeRange: [{ value: null, disabled: this.isEditable }, Validators.required]
        });
        this.initMoreInfo();
    }

    initMoreInfo() {
        this.MoreInfo = this.fb.group({
            irsubID: [{ value: null, disabled: this.isEditable }],
            acc_Type: [{ value: null, disabled: this.isEditable }],
            acc_Type_Oth: [{ value: null, disabled: this.isEditable }],
            road_State: [{ value: null, disabled: this.isEditable }],
            fatal_No: [{ value: null, disabled: this.isEditable }],
            serious_No: [{ value: null, disabled: this.isEditable }],
            slight_No: [{ value: null, disabled: this.isEditable }],
            damage: [{ value: null, disabled: this.isEditable }],
            danger_Type: [{ value: null, disabled: this.isEditable }],
            danger_Type_Oth: [{ value: null, disabled: this.isEditable }], //  Accident
            time_Of_Removal: [{ value: new Date(), disabled: this.isEditable }],
            obstacle_Type: [{ value: null, disabled: this.isEditable }],
            obstacle_Type_Oth: [{ value: null, disabled: this.isEditable }], // Obstacle
            roadWork_Type: [{ value: null, disabled: this.isEditable }],
            roadWork_Type_Oth: [{ value: null, disabled: this.isEditable }],
            permit: [{ value: null, disabled: this.isEditable }],
            contractor: [{ value: null, disabled: this.isEditable }],
            supervisor: [{ value: null, disabled: this.isEditable }],
            handphone: [{ value: null, disabled: this.isEditable }], // RoadWork
            weather_Event: [{ value: null, disabled: this.isEditable }],
            weather_Detail: [{ value: null, disabled: this.isEditable }],
            opinion: [{ value: null, disabled: this.isEditable }],
            visibility: [{ value: null, disabled: this.isEditable }] // BadWeather
        });
        this.towData.length = 0;
    }

    addTow(event) {
        this.isAddTow = true;
        this.clickEdit.emit(true);
        event.preventDefault();
        event.stopPropagation();
        let isEdit = false;
        if (this.towData.length > 0) {
            this.towData.forEach(item => {
                if (this.editCacheTow[item.ir_ID].edit === true) {
                    isEdit = true;
                }
            });
        }
        if (!isEdit) {
            const nextIrID = +(new Date().getTime() + '')
                .split('')
                .reverse()
                .join('')
                .substring(0, 5);
            let tempId = null;
            if (this.detailItem) {
                tempId = this.detailItem.irSub.irsubID;
            }
            const newTow = {
                isAdd: true,
                accident_ID: this.type === '1' ? tempId : null,
                obstacle_ID: this.type === '5' ? tempId : null,
                ir_ID: nextIrID,
                depart_Date: new Date(),
                notify_Date: new Date(),
                arri_Date: new Date(),
                officer_Name: this.UserInfo['name'],
                carPark_No: '',
                tc_Report_No: '',
                towed_Veh_Cat: 0,
                towed_Veh_Num: '',
                towing_Type: 0,
                towing_Veh_Cat: 0,
                towing_Veh_Num: null,
                towing_Company: null
            };
            this.towData = [newTow, ...this.towData];
            this.selectTow = newTow;
            this.updateEditCache(this.towData, this.editCacheTow, 'ir_ID');
            this.editCacheTow[nextIrID].edit = true;
            this.isEditTow = true;
        } else {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.save_notify' });
        }
    }

    // 选择一条tow
    chooseTow(ir_ID, i) {
        this.towData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                this.editCacheTow[ir_ID].active = true;
                this.selectTow = data;
            }
        });
    }

    // 编辑tow
    editTow(event) {
        event.preventDefault();
        event.stopPropagation();
        this.clickEdit.emit(true);
        let isEdit = false;
        if (this.towData.length > 0) {
            this.towData.forEach(item => {
                if (this.editCacheTow[item.ir_ID].edit === true) {
                    isEdit = true;
                }
            });
        }
        if (!isEdit) {
            if (this.selectTow) {
                this.isEditTow = true;
                this.editCacheTow[this.selectTow.ir_ID].edit = true;
                this.editCacheTow[this.selectTow.ir_ID].action = true;
            } else {
                this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.select_notify' });
            }
        } else {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.save_notify' });
        }
    }

    // 取消编辑
    cancelEditTow(event) {
        event.preventDefault();
        event.stopPropagation();
        this.clickEdit.emit(false);
        this.isEditTow = false;
        if (this.isAddTow) {
            this.towData = this.towData.filter(item => item.ir_ID !== this.selectTow.ir_ID);
            this.updateEditCache(this.towData, this.editCacheTow, 'ir_ID');
            this.selectTow = null;
            this.isAddTow = false;
        } else {
            const index = this.towData.findIndex(item => item.ir_ID === this.selectTow.ir_ID);
            this.editCacheTow[this.selectTow.ir_ID] = {
                data: { ...this.towData[index] },
                edit: false
            };
            this.getIRById(3);
        }
    }

    saveTow() {
        this.isAddTow = false;
        this.isEditTow = false;
        const index = this.towData.findIndex(item => item.ir_ID === this.selectTow.ir_ID);
        Object.assign(this.towData[index], this.editCacheTow[this.selectTow.ir_ID].data);
        this.editCacheTow[this.selectTow.ir_ID].edit = false;
    }

    ngOnInit() {
        this.initForm();
        this.initMoreInfo();
        this._setGisPosition();
        this.getUserInfo();
        this.getSelectionList();
        this.getZoneIdListByUser();
    }

    ngOnDestroy(): void {
        this.bully.resetBSubject();
        if (this.subscription) {
            this.bully.resetBSubject();
            this.subscription.unsubscribe();
        }
    }

    getUserInfo() {
        if (localStorage.getItem('role_id') && localStorage.getItem('user_name')) {
            this.UserInfo = {
                id: localStorage.getItem('role_id'),
                name: localStorage.getItem('user_name')
            };
        }
    }

    // 添加partner
    addPar(event) {
        this.clickEdit.emit(true);
        event.preventDefault();
        event.stopPropagation();
        let isEdit = false;
        if (this.partnerData.length > 0) {
            this.partnerData.forEach(partnerItem => {
                if (this.editCache[partnerItem.partnerID].edit === true) {
                    isEdit = true;
                }
            });
        }
        if (!isEdit) {
            const nextPartnerID = +(new Date().getTime() + '')
                .split('')
                .reverse()
                .join('')
                .substring(0, 5);
            const newPartner = {
                arri_Date: new Date(),
                depart_Date: new Date(),
                eta: new Date(),
                irId: this.ir_ID,
                jobId: '',
                notify_Date: new Date(),
                officer_Name: this.UserInfo['name'],
                partnerID: nextPartnerID,
                plateNos: '',
                type: 5,
                veh_Num: ''
            };
            this.partnerData = [newPartner, ...this.partnerData];
            this.selectPartner = newPartner;
            this.updateEditCache(this.partnerData, this.editCache, 'partnerID');
            this.editCache[nextPartnerID].edit = true;
            this.isEdit = true;
        } else {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.save_notify' });
        }
    }

    // 刷新partner
    refreshPar() {
        this.getIRById(1);
    }

    selectPar(partnerID, i) {
        // this.partnerData[index].active = true;
        this.partnerData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                this.editCache[partnerID].active = true;
                this.selectPartner = data;
            }
        });
    }

    // 编辑partner
    startEdit(event): void {
        event.preventDefault();
        event.stopPropagation();
        this.clickEdit.emit(true);
        let isEdit = false;
        if (this.partnerData.length > 0) {
            this.partnerData.forEach(partnerItem => {
                if (this.editCache[partnerItem.partnerID].edit === true) {
                    isEdit = true;
                }
            });
        }
        if (!isEdit) {
            if (this.selectPartner) {
                this.isEdit = true;
                this.editCache[this.selectPartner.partnerID].edit = true;
                this.editCache[this.selectPartner.partnerID].action = true;
            } else {
                this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.select_notify' });
            }
        } else {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.save_notify' });
        }
    }

    // 取消编辑
    cancelEditPar(event) {
        event.preventDefault();
        event.stopPropagation();
        this.clickEdit.emit(false);
        const index = this.partnerData.findIndex(item => item.partnerID === this.selectPartner.partnerID);
        this.editCache[this.selectPartner.partnerID] = {
            data: { ...this.partnerData[index] },
            edit: false
        };
        this.isEdit = false;
        this.selectPartner = null;
        this.getIRById(1);
    }

    onSave(event) {
        event.preventDefault();
        event.stopPropagation();
        const index = this.partnerData.findIndex(item => item.partnerID === this.selectPartner.partnerID);
        Object.assign(this.partnerData[index], this.editCache[this.selectPartner.partnerID].data);
        const { veh_Num, plateNos, arri_Date, depart_Date, notify_Date } = this.partnerData[index];
        if (!veh_Num || veh_Num === '') {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.validate_veh_Num' });
            return;
        }
        if (!plateNos || plateNos === '') {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.validate_plateNos' });
            return;
        }
        if (!arri_Date || arri_Date === '') {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.validate_arri_Date' });
            return;
        }
        if (!depart_Date || depart_Date === '') {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.validate_depart_Date' });
            return;
        }
        if (!notify_Date || notify_Date === '') {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.validate_notify_Date' });
            return;
        }
        this.partnerData = this.partnerData.map(item => {
            delete item.active;
            return item;
        });
        this.saveOrUpdateIRPartner(index);
    }

    // 删除partner
    deletePar(event) {
        event.preventDefault();
        event.stopPropagation();
        if (!this.selectPartner) {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.select_notify' });
        } else {
            const tempTranslate = [
                { title: 'TrafficManagement.IncidentRecord.Delete Message' },
                { title: 'TrafficManagement.IncidentRecord.Are you sure you want to remove this partner' },
                { title: 'TrafficManagement.IncidentRecord.OK' },
                { title: 'TrafficManagement.NO' }
            ];
            tempTranslate.forEach(item => {
                this.translate.get(item.title).subscribe((res: string) => {
                    item.title = res || '';
                });
            });
            this.modalService.confirm({
                nzTitle: '<i class="iconfont icon-delete" style="font-size:24px"></i>' + tempTranslate[0].title,
                nzContent: '<p style="font-size:24px">' + tempTranslate[1].title + '?</p>',
                nzOkText: tempTranslate[2].title,
                nzOnOk: () => {
                    this.deleteIrPartner(this.selectPartner.partnerID);
                },
                nzCancelText: tempTranslate[3].title,
                nzOnCancel: () => {}
            });
        }
    }

    // 删除partner调用接口
    deleteIrPartner(partnerId) {
        this.incidentService.deleteIrPartner(partnerId).subscribe(
            res => {
                if (res['messagecode'] === '000000') {
                    this.getIRById(1);
                    this.selectPartner = null;
                    this.message.create('success', `Delete partner successfully!`);
                } else {
                    this.message.create('error', `Failed to delete partner!`);
                }
            },
            _error => {
                this.message.remove('Failed to delete partner');
            }
        );
    }

    // 保存partner调用接口
    saveOrUpdateIRPartner(index) {
        this.incidentService.saveOrUpdateIRPartner(this.partnerData).subscribe(
            res => {
                if (res['messagecode'] === '000000') {
                    this.editCache[this.partnerData[index].partnerID].edit = false;
                    this.selectPartner = null;
                    this.isEdit = false;
                    this.partnerData = res.data || [];
                    this.partnerData.sort((a, b) => b.partnerID - a.partnerID);
                    this.updateEditCache(this.partnerData, this.editCache, 'partnerID');
                    this.message.create('success', `Save successfully!`);
                } else {
                    this.message.create('error', `Failed to save!`);
                }
            },
            _error => {
                this.message.create('error', 'Failed to save!');
            }
        );
    }

    //
    updateEditCache(array, editCacheData, id): void {
        array.forEach(item => {
            editCacheData[item[id]] = {
                edit: false,
                data: { ...item },
                active: false
            };
        });
    }

    // 获取partner接口
    getIRById(type) {
        type === 1 ? (this.partnerLoading = true) : (this.commentLoading = true);
        this.incidentService.getIRById(this.ir_ID).subscribe(res => {
            type === 1 ? (this.partnerLoading = false) : (this.commentLoading = false);
            if (res['messagecode'] === '000000') {
                if (type === 1) {
                    this.partnerData = res.data.partner || [];
                    if (this.partnerData.length > 0) {
                        this.partnerData.forEach(partnerItem => {
                            partnerItem.arri_Date = new Date(partnerItem.arri_Date);
                            partnerItem.depart_Date = new Date(partnerItem.depart_Date);
                            partnerItem.notify_Date = new Date(partnerItem.notify_Date);
                        });
                    }
                    this.partnerData.sort((a, b) => {
                        return b.partnerID - a.partnerID;
                    });
                    this.updateEditCache(this.partnerData, this.editCache, 'partnerID');
                }
                if (type === 2) {
                    this.commentsData = res.data.comments;
                    this.commentsData.sort((a, b) => {
                        return b.id - a.id;
                    });
                    this.updateEditCache(this.commentsData, this.editCacheComment, 'id');
                }
                if (type === 3) {
                    const towData = res.data.irSub.tow;
                    this.selectTow = null;
                    if (towData && towData.length > 0) {
                        this.towData = towData;
                        this.towData.sort((a, b) => {
                            return b.ir_ID - a.ir_ID;
                        });
                        this.updateEditCache(this.towData, this.editCacheTow, 'ir_ID');
                    }
                }
            } else {
                this.message.create('error', `Failed to save!`);
            }
        });
    }

    selectCom(id, i) {
        this.commentsData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                this.editCacheComment[id].active = true;
                this.selectComment = data;
            }
        });
    }

    // 添加comments
    addCom(event) {
        event.preventDefault();
        event.stopPropagation();
        this.clickEdit.emit(true);
        let isEdit = false;
        if (this.commentsData.length > 0) {
            this.commentsData.forEach(commentsItem => {
                if (this.editCacheComment[commentsItem.id].edit === true) {
                    isEdit = true;
                }
            });
        }
        if (!isEdit) {
            const nextCommentId = +(new Date().getTime() + '')
                .split('')
                .reverse()
                .join('')
                .substring(0, 6);
            const newComment = {
                content: '',
                createTime: new Date(),
                flag: 0,
                id: nextCommentId,
                irId: this.ir_ID,
                updateTime: new Date(),
                userId: this.UserInfo.id,
                userName: this.UserInfo.name
            };
            this.commentsData = [newComment, ...this.commentsData];
            this.updateEditCache(this.commentsData, this.editCacheComment, 'id');
            this.editCacheComment[nextCommentId].edit = true;
            this.selectComment = newComment;
            this.isEditComment = true;
        } else {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.save_notify' });
        }
    }

    // 保存comments
    saveCom(event) {
        event.preventDefault();
        event.stopPropagation();
        const index = this.commentsData.findIndex(item => item.id === this.selectComment.id);
        Object.assign(this.commentsData[index], this.editCacheComment[this.selectComment.id].data);
        const { content } = this.commentsData[index];
        if (!content || content === '') {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.validate_description' });
            return;
        }
        this.commentsData = this.commentsData.map(item => {
            delete item.active;
            return item;
        });
        this.saveOrUpdateIRComment(index);
    }

    cancelEditCom(event) {
        event.preventDefault();
        event.stopPropagation();
        this.clickEdit.emit(false);
        const index = this.commentsData.findIndex(item => item.id === this.selectComment.id);
        this.editCacheComment[this.selectComment.id] = {
            data: { ...this.commentsData[index] },
            edit: false
        };
        this.isEditComment = false;
        this.selectComment = null;
        this.getIRById(2);
    }

    // 刷新comments
    refreshCom() {
        this.getIRById(2);
    }

    // 编辑comments
    editCom(event) {
        event.preventDefault();
        event.stopPropagation();
        this.clickEdit.emit(true);
        let isEdit = false;
        if (!this.selectComment) {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.select_notify' });
        } else {
            if (this.commentsData.length > 0) {
                this.commentsData.forEach(commentItem => {
                    if (this.editCacheComment[commentItem.id].edit === true) {
                        isEdit = true;
                    }
                });
            }
            if (!isEdit) {
                if (this.selectComment) {
                    this.isEditComment = true;
                    this.editCacheComment[this.selectComment.id].edit = true;
                    this.editCacheComment[this.selectComment.id].action = true;
                } else {
                    this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.select_notify' });
                }
            } else {
                this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.save_notify' });
            }
        }
    }

    // 删除comments
    deleteCom(event) {
        event.preventDefault();
        event.stopPropagation();
        if (!this.selectComment) {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.select_notify' });
        } else {
            const tempTranslate = [
                { title: 'TrafficManagement.IncidentRecord.Delete Message' },
                { title: 'TrafficManagement.IncidentRecord.Are you sure you want to remove this comment' },
                { title: 'TrafficManagement.IncidentRecord.OK' },
                { title: 'TrafficManagement.IncidentRecord.NO' }
            ];
            tempTranslate.forEach(item => {
                this.translate.get(item.title).subscribe((res: string) => {
                    item.title = res || '';
                });
            });
            this.modalService.confirm({
                nzTitle: '<i class="iconfont icon-delete" style="font-size:24px"></i>' + tempTranslate[0].title,
                nzContent: '<p style="font-size:24px">' + tempTranslate[1].title + '?</p>',
                nzOkText: tempTranslate[2].title,
                nzOnOk: () => {
                    this.deleteIRComments(this.selectComment.id);
                },
                nzCancelText: tempTranslate[3].title,
                nzOnCancel: () => {}
            });
        }
    }

    // 删除comments接口
    deleteIRComments(id) {
        this.incidentService.deleteIRComments(id).subscribe(
            res => {
                if (res['messagecode'] === '000000') {
                    this.selectComment = null;
                    this.message.create('success', `Delete comment successfully!`);
                    this.getIRById(2);
                } else {
                    this.message.create('error', `Failed to comment partner!`);
                }
            },
            _error => {
                this.message.create('error', `Failed to comment partner!`);
            }
        );
    }

    saveOrUpdateIRComment(index) {
        this.incidentService.saveOrUpdateIRComment(this.commentsData).subscribe(
            res => {
                if (res['messagecode'] === '000000') {
                    this.editCacheComment[this.commentsData[index].id].edit = false;
                    this.selectComment = null;
                    this.isEditComment = false;
                    this.commentsData = res.data || [];
                    this.commentsData.sort((a, b) => b.id - a.id);
                    this.updateEditCache(this.commentsData, this.editCacheComment, 'id');
                    this.message.create('success', `Save successfully!`);
                } else {
                    this.message.create('error', `Failed to save!`);
                }
            },
            _error => {
                this.message.create('error', `Failed to save!`);
            }
        );
    }

    // 初始化详情
    initIrInfoDetail(item) {
        this.isEdit = false;
        this.isEditComment = false;
        this.detailItem = item;
        const partner = (item && item.partner) || [];
        this.partnerData = [...partner];
        this.partnerData.forEach(partnerItem => {
            partnerItem.arri_Date = new Date(partnerItem.arri_Date);
            partnerItem.depart_Date = new Date(partnerItem.depart_Date);
            partnerItem.notify_Date = new Date(partnerItem.notify_Date);
        });
        this.partnerData.sort((a, b) => {
            return b.partnerID - a.partnerID;
        });
        this.updateEditCache(this.partnerData, this.editCache, 'partnerID');
        const comments = (item && item.comments) || [];
        this.commentsData = [...comments];
        this.commentsData.sort((a, b) => {
            return b.id - a.id;
        });
        this.updateEditCache(this.commentsData, this.editCacheComment, 'id');
        this.isTaskFromMap = false; // 每次有新的新建或编辑重置这个值
        this.laneBlockagesList = []; // 每次编辑或新建都初始化
        if (item != null) {
            item.length === 0 ? (item = null) : (item = item);
            if (item === null) {
                return;
            }
            this.isUpdate = true;
            this.changeIncidentType(item.type);

            // 从其他页面调过来的创建任务
            if (item.fromGis !== undefined) {
                this.isUpdate = false;
                if (item.fromGis) {
                    this.isTaskFromMap = true;
                }
            } else {
                this.ir_ID = item.ir_ID;
            }
            if (item.type === 1 || item.type === 2 || item.type === 5 || item.type === 7) {
                this.ifMoreInfoShow = true;
            } else {
                this.ifMoreInfoShow = false;
            }
            if (item.veri_State === 0) {
                this.isFinishShow = true;
            } else {
                this.isFinishShow = false;
            }
            if (item.veri_State === 1) {
                this.isCloseShow = true;
            } else {
                this.isCloseShow = false;
            }
            this.isEditable = true;
            if (item.lane_Blockage != null) {
                this.laneBlockagesList = [...item.lane_Blockage];
            }
            this.createAccess = item.access;
            this.validateForm.patchValue({
                ir_ID: item.ir_ID,
                veri_State: '' + item.veri_State,
                cause_IR_ID: item.cause_IR_ID,
                source: '' + item.source,
                type: '' + item.type,
                subType: item.subType,
                zone_ID: item.zone_ID,
                cause: item.cause,
                road_Name: item.road_Name,
                location_Type: item.location_Type,
                location_SubType: item.location_SubType,
                direction: item.direction,
                startCoor: item.start_X_Coor + ' , ' + item.start_Y_Coor,
                start_X_Coor: item.start_X_Coor,
                start_Y_Coor: item.start_Y_Coor,
                endCoor: item.end_X_Coor && item.end_X_Coor + ' , ' + item.end_Y_Coor,
                end_X_Coor: item.end_X_Coor,
                end_Y_Coor: item.end_Y_Coor,
                q_End_Link_ID: item.q_End_Link_ID,
                QendCoor: item.q_End_X_Coor && item.q_End_X_Coor + ' , ' + item.q_End_Y_Coor,
                q_End_X_Coor: item.q_End_X_Coor,
                q_End_Y_Coor: item.q_End_Y_Coor,
                QEPLatitude: item.q_End_Y_Coor,
                start_Time: item.start_Time ? new Date(item.start_Time) : null,
                end_Time: item.end_Time ? new Date(item.end_Time) : null,
                q_Start_Time: item.q_Start_Time ? new Date(item.q_Start_Time) : null,
                q_End_Time: item.q_End_Time ? new Date(item.q_End_Time) : null,
                eTime: item.eTime ? new Date(item.eTime) : null,
                remark: item.remark,
                lane_Blockage: item.lane_Blockage,
                irSub: null,
                access: item.access,
                incidentTimeRange: item.start_Time ? [new Date(item.start_Time), new Date(item.end_Time)] : null,
                QTimeRange: item.q_Start_Time ? [new Date(item.q_Start_Time), new Date(item.q_Start_Time)] : null
            });
            for (const key in this.validateForm.controls) {
                if (this.validateForm.controls.hasOwnProperty(key)) {
                    this.validateForm.controls[key].disable();
                }
            }
            this.fillMoreInfo(item);
        } else {
            this.isEditable = false;
            this.validateForm.reset();
            this.MoreInfo.reset();
            this.isUpdate = false;
            for (const key in this.validateForm.controls) {
                if (this.validateForm.controls.hasOwnProperty(key)) {
                    this.validateForm.controls[key].enable();
                }
            }
            for (const key in this.MoreInfo.controls) {
                if (this.MoreInfo.controls.hasOwnProperty(key)) {
                    this.MoreInfo.controls[key].disable();
                }
            }
        }
    }

    fillMoreInfo(item) {
        if (item.irSub) {
            const data = item.irSub;
            this.MoreInfo.patchValue({
                irsubID: data.irsubID,
                acc_Type: data.acc_Type,
                acc_Type_Oth: data.acc_Type_Oth,
                road_State: data.road_State,
                fatal_No: data.fatal_No,
                serious_No: data.serious_No,
                slight_No: data.slight_No,
                damage: data.damage,
                danger_Type: data.danger_Type,
                danger_Type_Oth: data.danger_Type_Oth, //  Accident
                time_Of_Removal: new Date(data.time_Of_Removal),
                obstacle_Type: data.obstacle_Type,
                obstacle_Type_Oth: data.obstacle_Type_Oth, // Obstacle
                roadWork_Type: data.roadWork_Type,
                roadWork_Type_Oth: data.roadWork_Type_Oth,
                permit: data.permit,
                contractor: data.contractor,
                supervisor: data.supervisor,
                handphone: data.handphone, // RoadWork
                weather_Event: data.weather_Event,
                weather_Detail: data.weather_Detail,
                opinion: data.opinion,
                visibility: data.visibility // BadWeather
            });
            if (data.tow && data.tow.length > 0) {
                const towData = (data && data.tow) || [];
                const newTowData = [];
                towData.forEach(towItem => {
                    newTowData.push({
                        accident_ID: towItem.accident_ID,
                        towing_Veh_Cat: towItem.towing_Veh_Cat,
                        towing_Veh_Num: towItem.towing_Veh_Num,
                        towing_Company: towItem.towing_Company,
                        ir_ID: towItem.ir_ID,
                        depart_Date: towItem.depart_Date,
                        notify_Date: towItem.notify_Date,
                        arri_Date: towItem.arri_Date,
                        officer_Name: towItem.officer_Name,
                        carPark_No: towItem.carPark_No,
                        tc_Report_No: towItem.tc_Report_No,
                        towed_Veh_Cat: towItem.towed_Veh_Cat,
                        towing_Type: towItem.towing_Type,
                        towed_Veh_Num: towItem.towed_Veh_Num,
                        obstacle_ID: towItem.obstacle_ID
                    });
                });
                this.towData = [...newTowData];
                this.towData.forEach(towItem => {
                    towItem.arri_Date = new Date(towItem.arri_Date);
                    towItem.depart_Date = new Date(towItem.depart_Date);
                    towItem.notify_Date = new Date(towItem.notify_Date);
                });
                this.updateEditCache(this.towData, this.editCacheTow, 'ir_ID');
            }
            if (this.isClickEdit) {
                for (const key in this.MoreInfo.controls) {
                    if (this.MoreInfo.controls.hasOwnProperty(key)) {
                        this.MoreInfo.controls[key].enable();
                    }
                }
            } else {
                for (const key in this.MoreInfo.controls) {
                    if (this.MoreInfo.controls.hasOwnProperty(key)) {
                        this.MoreInfo.controls[key].disable();
                    }
                }
            }
        }
    }

    editForm() {
        this.isClickEdit = true;
        this.clickEdit.emit(true);
        for (const key in this.validateForm.controls) {
            if (this.validateForm.controls.hasOwnProperty(key)) {
                this.validateForm.controls[key].enable();
                // if (this.isUpdate) {
                this.validateForm.controls['ir_ID'].disable();
                // }
            }
        }
        for (const key in this.MoreInfo.controls) {
            if (this.MoreInfo.controls.hasOwnProperty(key)) {
                this.MoreInfo.controls[key].enable();
            }
        }
    }

    cancelEditFunc() {
        if (!this.isUpdate) {
            this.cancelEdit.emit('cancel');
        } else {
            this.initIrInfoDetail(this.detailItem);
        }
        this.clickBtn = null;
        this.isClickEdit = false;
        this.clickEdit.emit(false);
    }

    showModal(): void {
        this.isVisible = true;
    }

    moreInfoHandleOk(): void {
        let isEdit = false;
        this.towData.forEach(item => {
            if (this.editCacheTow[item.ir_ID].edit === true) {
                isEdit = true;
            }
        });
        if (!isEdit) {
            this.isVisible = false;
        } else {
            this.msg.notify({ type: 'warning', path: 'TrafficManagement.IncidentRecord.save_notify' });
        }
    }

    moreInfoHandleCancel(): void {
        if (!this.isUpdate) {
            this.initMoreInfo();
        } else {
            this.fillMoreInfo(this.detailItem);
        }
        this.isVisible = false;
    }

    handleOk(): void {
        this.isVisible = false;
    }

    handleCancel(): void {
        if (!this.isUpdate) {
            this.initMoreInfo();
        } else {
            this.initIrInfoDetail(this.detailItem);
        }
        this.isVisible = false;
    }

    editLaneBlockages(laneIndex, seIndex) {
        if (!this.isClickEdit) {
            return;
        }
        if (seIndex === 2) {
            this.deleteLaneBlockages(laneIndex);
            return;
        }
        this.laneBlockagesList[laneIndex] = seIndex;
    }

    deleteLaneBlockages(laneIndex) {
        if (!this.isClickEdit) {
            return;
        }
        this.laneBlockagesList.splice(laneIndex, 1);
    }

    addLaneBlockages(idx) {
        if (!this.isClickEdit) {
            return;
        }
        this.laneBlockagesList.push(idx);
    }

    finish(param?) {
        const value = this.queryDataForm(this.validateForm.value);
        value.access = {
            ir_AccessType: false,
            userID: '2051',
            userType: null
        };
        const header = {
            zoneId: this.zoneIdList.join(','),
            isFource: param ? param : false
        };
        value.veri_State = 2;
        const query = this.incidentService.finishIrDetail(value, header);
        query.subscribe(
            (res: any) => {
                if (res.messagecode === '900103') {
                    this.isForceFinishVisible = true;
                    return;
                } else {
                    this.message.create('success', `Incident record finished!`);
                    this.cancelEdit.emit('cancel');
                    this.irFinished.emit();
                }
            },
            (_error: any) => {
                this.message.create('error', `Finish incident record failed!`);
            }
        );
    }

    queryDataForm(item) {
        const value = this.tools.isClone(item);
        if (value.startCoor !== null) {
            const startPoint = value.startCoor.split(',');
            value.start_X_Coor = startPoint[0];
            value.start_Y_Coor = startPoint[1];
        }
        if (value.endCoor !== null) {
            const endPoint = value.endCoor.split(',');
            value.end_X_Coor = endPoint[0];
            value.end_Y_Coor = endPoint[1];
        }
        if (value.QendCoor !== null) {
            const QendPoint = value.QendCoor.split(',');
            value.q_End_X_Coor = QendPoint[0];
            value.q_End_Y_Coor = QendPoint[1];
        }
        if (this.laneBlockagesList !== null) {
            value.lane_Blockage = this.laneBlockagesList.join('');
            if (value.lane_Blockage) {
                this.validateForm.patchValue({ lane_Blockage: value.lane_Blockage });
            }
        }
        if (value.incidentTimeRange !== null && value.incidentTimeRange.length !== 0) {
            // value.start_Time = new Date(value.incidentTimeRange[0]).getTime();
            // value.end_Time = new Date(value.incidentTimeRange[1]).getTime();
            value.start_Time = new Date(moment(value.incidentTimeRange[0]).format('YYYY-MM-DD 00:00:00')).getTime();
            value.end_Time = new Date(moment(value.incidentTimeRange[1]).format('YYYY-MM-DD 23:59:59')).getTime();
        }
        if (value.QTimeRange !== null && value.QTimeRange.length !== 0) {
            // value.q_Start_Time = new Date(value.QTimeRange[0]).getTime();
            // value.q_End_Time = new Date(value.QTimeRange[1]).getTime();
            value.q_Start_Time = new Date(moment(value.QTimeRange[0]).format('YYYY-MM-DD 00:00:00')).getTime();
            value.q_End_Time = new Date(moment(value.QTimeRange[1]).format('YYYY-MM-DD 23:59:59')).getTime();
        }
        return value;
    }

    getGisPosition(key) {
        // const url = `${location.origin}/#/gis`;
        // window.open(url, 'getPosition');
        if (!this.isClickEdit) {
            return;
        }
        this.clickBtn = key;
        const bully = {
            type: MESSAGE_CHANNEL.CCM_CHANNEL,
            data: {
                data: key
            }
        };
        this.bully.registerBroadcastSend(MESSAGE_CHANNEL.CCM_CHANNEL, bully);
    }

    private _setGisPosition() {
        this.subscription = this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.MAP_CHANNEL).subscribe(res => {
            if (res.type === MESSAGE_CHANNEL.MAP_CHANNEL) {
                const features = res['data']['features'];
                const dataType = res['data']['dataType'];
                this.clickBtn = null;
                const value = {
                    [dataType]: features['longitude'] + ',' + features['latitude']
                };
                switch (dataType) {
                    case 'startCoor':
                        value['road_Name'] = features['roadName'];
                        break;
                    case 'QendCoor':
                        value['q_End_Link_ID'] = features['linkID'];
                        break;
                }
                this.validateForm.patchValue(value);
            }
        });
    }

    changeIncidentType(event) {
        this.type = event;
        this.initMoreInfo();
        switch (event) {
            case '1': // Accident
                this.showMoreInfoTable = true;
                this.ifMoreInfoShow = true;
                this.modalWidth = '17.94rem';
                this.modalTableSpan = 19;
                this.modalSpan = 5;
                break;
            case '5': // Obstacle
                this.ifMoreInfoShow = true;
                this.showMoreInfoTable = true;
                this.modalWidth = '17.94rem';
                this.modalTableSpan = 19;
                this.modalSpan = 5;
                break;
            case '7': // RoadWork
                this.ifMoreInfoShow = true;
                this.showMoreInfoTable = false;
                this.modalWidth = '4.84rem';
                this.modalTableSpan = 0;
                this.modalSpan = 24;
                break;
            case '2': // BadWeather
                this.ifMoreInfoShow = true;
                this.showMoreInfoTable = false;
                this.modalWidth = '4.84rem';
                this.modalTableSpan = 0;
                this.modalSpan = 24;
                break;
            default:
                this.ifMoreInfoShow = false;
                this.showMoreInfoTable = false;
                this.modalWidth = '4.84rem';
                this.modalTableSpan = 0;
                this.modalSpan = 24;
                break;
        }
        if (this.isClickEdit) {
            for (const key in this.MoreInfo.controls) {
                if (this.MoreInfo.controls.hasOwnProperty(key)) {
                    this.MoreInfo.controls[key].enable();
                }
            }
        } else {
            for (const key in this.MoreInfo.controls) {
                if (this.MoreInfo.controls.hasOwnProperty(key)) {
                    this.MoreInfo.controls[key].disable();
                }
            }
        }
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };
}
